"""
#!/usr/bin/python3
# coding:utf-8            
#
# Copyright (C) 2024 - 2024 Jasonakeke， Inc. All Rights Reserved 
# @Desc	   ：自定义 Web 框架
# @Time    : 2024/8/1 22:07
# @Author  : Code_By_Jasonakeke
# @Email   : 2284037977@qq.com
# @File    : MyFramework.py
# @IDE     : PyCharm
"""
from functools import wraps
from time import strftime, localtime

# 定义路由表
route_list = []


# route_list = {
# ('/index.html', index),
# ('/userinfo.html', user_info),
# }

# 调用一个带参数的装饰器
def route(request_path):
	"""
	:param request_path: URL 请求
	:return:
	"""

	def add_route(func):
		# 添加路由到路由表
		route_list.append((request_path, func))

		@wraps(func)
		def invoke(*arg, **kwargs):
			# 调用指定的处理函数并返回
			return func(*arg, **kwargs)

		return invoke

	return add_route


# 处理动态资源请求
def handle_request(params):
	request_path = params['request_path']
	for path, func in route_list:
		if request_path == path:
			return func()
	else:
		return page_not_found()


# 当前的请求路径有与之对应的动态响应
# if request_path == '/index.html':
# 	response = index()
# 	return response
# elif request_path == '/userinfo.html':
# 	response = user_info()
# 	return response
# else:
# return page_not_found()


# 专门处理 index.html 的请求
@route('/index.html')
def index():
	response_body = None
	date = strftime('%Y-%m-%d %H:%M:%S', localtime())
	# response_body = data
	with open('template/index.html', 'r', encoding = 'utf-8') as f:
		response_body = f.read()
	response_body = response_body.replace('{%datas%}', date)
	response_first_line = 'HTTP/1.1 200 OK\r\n'
	# 响应头
	response_header = 'Server: keke\r\n'
	response = (response_first_line + response_header + '\r\n' + response_body).encode('utf-8')
	return response


# 处理没有找到对应的动态资源
def page_not_found():
	# 浏览器想读取的文件可能不存在
	with open('static/404.html', 'rb') as f:
		# 响应主体页面
		response_body = f.read()
	response_first_line = 'HTTP/1.1 404 Not Found\r\n'
	# 响应头
	response_header = 'Server: keke\r\n'
	response = (response_first_line + response_header + '\r\n').encode('utf-8') + response_body
	return response


@route('/userinfo.html')
def user_info():
	response_body = None
	date = strftime('%Y-%m-%d %H:%M:%S', localtime())
	# response_body = data
	with open('template/user_info.html', 'r', encoding = 'utf-8') as f:
		response_body = f.read()
	response_body = response_body.replace('{%datas%}', date)
	response_first_line = 'HTTP/1.1 200 OK\r\n'
	# 响应头
	response_header = 'Server: keke\r\n'
	response = (response_first_line + response_header + '\r\n' + response_body).encode('utf-8')
	return response
